/**
 * @date 2006-2-23 17:27:48
 *
 */
package org.nanhill.moo.web.controller;

import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nanhill.moo.domain.Category;
import org.nanhill.moo.domain.Cost;
import org.nanhill.moo.domain.Favor;
import org.nanhill.moo.service.CategoryService;
import org.nanhill.moo.service.CostService;
import org.nanhill.moo.service.FavorService;
import org.nanhill.moo.web.UserSession;
import org.nanhill.moo.web.form.CreateFavorForm;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author alin [xalinx at gmail dot com]
 * 
 */
public class CreateFavorController extends NamedFormController {
	private static final String FORM_NAME = "createFavorForm";

	private FavorService favorService;

	public void setFavorService(FavorService favorService) {
		this.favorService = favorService;
	}

	private CategoryService categoryService;

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	private CostService costService;

	public void setCostService(CostService costService) {
		this.costService = costService;
	}

	public CreateFavorController() {
		setCommandClass(CreateFavorForm.class);
		setCommandName(FORM_NAME);
		setSubmitType(FORM_NAME);
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		CreateFavorForm form = CreateFavorForm.getInstance();
		Collection<Category> allCg = categoryService.loadCachedRootChilds();
		form.setCategories(allCg);
		Cost[] allCs = costService.loadAll();
		form.setCosts(allCs);
		return form;
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		CreateFavorForm form = (CreateFavorForm) command;

		// { 创建新Favor
		Favor favor = new Favor();
		Category cg = categoryService.loadById(form.getCategory());
		if (null == cg) {
			errors.rejectValue("category", "errors.notfound", null, null);
			return this.showForm(request, response, errors);
		}
		favor.setCategory(cg);
		Cost cs = costService.load(form.getCost());
		if (null == cs) {
			errors.rejectValue("cost", "errors.notfound", null, null);
			return this.showForm(request, response, errors);
		}
		favor.setCost(cs);
		favor.setTitle(form.getTitle());
		favor.setContent(form.getContent());
		favor.setAuthor(UserSession.getUserSession(request).getLogin());
		favor.setCreateTime(new Date());
		// }

		this.favorService.open(favor);

		return new ModelAndView(this.getSuccessView());
	}

}
